﻿using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.SS.Util;
using NPOI.XSSF.UserModel;

namespace Frame.Core.Common.Common
{
    public class NpoiHelper
    {
        #region 从Excel中读数据到DataTable  
        /// <summary>  
        /// 从Excel中获取数据到DataTable  
        /// </summary>  
        /// <param name="strFileName">Excel文件全路径(服务器路径)</param>  
        /// <param name="extension">Excel文件的扩展名</param>  
        /// <param name="sheetName">要获取数据的工作表名称</param>  
        /// <param name="headerRowIndex">工作表标题行所在行号(从0开始)</param>  
        /// <returns></returns>  
        public static DataTable RenderDataTableFromExcel(string strFileName, string extension, string sheetName, int headerRowIndex)
        {
            using (FileStream file = new FileStream(strFileName, FileMode.Open, FileAccess.Read))
            {
                IWorkbook workbook;
                if (extension.Equals(".xls") || extension.Equals(".XLS"))
                {
                    workbook = new HSSFWorkbook(file);
                }
                else
                {
                    workbook = new XSSFWorkbook(file);
                }
                return RenderDataTableFromExcel(workbook, sheetName, headerRowIndex);
            }
        }

        /// <summary>  
        /// 从Excel中获取数据到DataTable  
        /// </summary>  
        /// <param name="strFileName">Excel文件全路径(服务器路径)</param>  
        /// <param name="extension">Excel文件的扩展名</param>  
        /// <param name="sheetIndex">要获取数据的工作表序号(从0开始)</param>  
        /// <param name="headerRowIndex">工作表标题行所在行号(从0开始)</param>  
        /// <returns></returns>  
        public static DataTable RenderDataTableFromExcel(string strFileName, string extension, int sheetIndex, int headerRowIndex)
        {
            using (FileStream file = new FileStream(strFileName, FileMode.Open, FileAccess.Read))
            {
                IWorkbook workbook;
                if (extension.Equals(".xls") || extension.Equals(".XLS"))
                {
                    workbook = new HSSFWorkbook(file);
                }
                else
                {
                    workbook = new XSSFWorkbook(file);
                }

                string sheetName = workbook.GetSheetName(sheetIndex);
                return RenderDataTableFromExcel(workbook, sheetName, headerRowIndex);
            }
        }

        /// <summary>  
        /// 从Excel中获取数据到DataTable  
        /// </summary>  
        /// <param name="excelFileStream">Excel文件流</param>  
        /// <param name="sheetName">要获取数据的工作表名称</param>  
        /// <param name="headerRowIndex">工作表标题行所在行号(从0开始)</param>  
        /// <returns></returns>  
        public static DataTable RenderDataTableFromExcel(Stream excelFileStream, string sheetName, int headerRowIndex)
        {
            IWorkbook workbook = new HSSFWorkbook(excelFileStream);
            excelFileStream.Close();
            return RenderDataTableFromExcel(workbook, sheetName, headerRowIndex);
        }

        /// <summary>  
        /// 从Excel中获取数据到DataTable  
        /// </summary>  
        /// <param name="excelFileStream">Excel文件流</param>  
        /// <param name="sheetIndex">要获取数据的工作表序号(从0开始)</param>  
        /// <param name="headerRowIndex">工作表标题行所在行号(从0开始)</param>  
        /// <returns></returns>  
        public static DataTable RenderDataTableFromExcel(Stream excelFileStream, int sheetIndex, int headerRowIndex)
        {
            IWorkbook workbook = new HSSFWorkbook(excelFileStream);
            excelFileStream.Close();
            string sheetName = workbook.GetSheetName(sheetIndex);
            return RenderDataTableFromExcel(workbook, sheetName, headerRowIndex);
        }

        /// <summary>  
        /// 从Excel中获取数据到DataTable  
        /// </summary>  
        /// <param name="workbook">要处理的工作薄</param>  
        /// <param name="sheetName">要获取数据的工作表名称</param>  
        /// <param name="headerRowIndex">工作表标题行所在行号(从0开始)</param>  
        /// <returns></returns>  
        public static DataTable RenderDataTableFromExcel(IWorkbook workbook, string sheetName, int headerRowIndex)
        {
            ISheet sheet = workbook.GetSheet(sheetName);
            DataTable table = new DataTable();
            try
            {
                IRow headerRow = sheet.GetRow(headerRowIndex);
                int cellCount = headerRow.LastCellNum;

                for (int i = headerRow.FirstCellNum; i < cellCount; i++)
                {
                    DataColumn column = new DataColumn(headerRow.GetCell(i).StringCellValue);
                    table.Columns.Add(column);
                }

                #region 循环各行各列,写入数据到DataTable  
                for (int i = (sheet.FirstRowNum + 1); i < sheet.LastRowNum + 1; i++)
                {
                    IRow row = sheet.GetRow(i);
                    DataRow dataRow = table.NewRow();
                    for (int j = row.FirstCellNum; j < cellCount; j++)
                    {
                        ICell cell = row.GetCell(j);
                        if (cell == null)
                        {
                            dataRow[j] = null;
                        }
                        else
                        {
                            switch (cell.CellType)
                            {
                                case CellType.Blank:
                                    dataRow[j] = null;
                                    break;
                                case CellType.Boolean:
                                    dataRow[j] = cell.BooleanCellValue;
                                    break;
                                case CellType.Numeric:
                                    dataRow[j] = cell.ToString();
                                    break;
                                case CellType.String:
                                    dataRow[j] = cell.StringCellValue;
                                    break;
                                case CellType.Error:
                                    dataRow[j] = cell.ErrorCellValue;
                                    break;
                                default:
                                    dataRow[j] = "=" + cell.CellFormula;
                                    break;
                            }
                        }
                    }
                    table.Rows.Add(dataRow);
                    //dataRow[j] = row.GetCell(j).ToString();  
                }
                #endregion
            }
            catch (Exception ex)
            {
                table.Clear();
                table.Columns.Clear();
                table.Columns.Add("出错了");
                DataRow dr = table.NewRow();
                dr[0] = ex.Message;
                table.Rows.Add(dr);
                return table;
            }

            #region 清除最后的空行  
            for (int i = table.Rows.Count - 1; i > 0; i--)
            {
                bool isnull = true;
                for (int j = 0; j < table.Columns.Count; j++)
                {
                    if (table.Rows[i][j] != null)
                    {
                        if (table.Rows[i][j].ToString() != "")
                        {
                            isnull = false;
                            break;
                        }
                    }
                }
                if (isnull)
                {
                    table.Rows[i].Delete();
                }
            }
            #endregion
            return table;
        }


        /// <summary>
        /// 到合并功能的导出xls，默认参照第一列做合并，如果第一列不合并，那么其他列也不合并
        /// </summary>
        /// <param name="dt">DataTable</param>
        /// <param name="sheetname">sheetname</param>
        /// <param name="noColumns">从列尾开始有多少列不合并</param>
        public static MemoryStream NpoiExcel(DataTable dt, string sheetname, int noColumns)
        {
            var book = new HSSFWorkbook();
            var sheet = book.CreateSheet(sheetname);
            var headerrow = sheet.CreateRow(0);
            ICellStyle style = book.CreateCellStyle();

            var dateStyle = book.CreateCellStyle();
            var format = book.CreateDataFormat();
            dateStyle.DataFormat = format.GetFormat("yyyy-mm-dd");

            //添加列名
            for (int i = 0; i < dt.Columns.Count; i++)
            {
                ICell cell = headerrow.CreateCell(i);
                cell.CellStyle = style;
                cell.SetCellValue(dt.Columns[i].ColumnName);
            }
            //添加第一行数据
            var row = sheet.CreateRow(1);
            for (int j = 0; j < dt.Columns.Count; j++)
            {
                string cellText = dt.Rows[0][j].ToString();

                var newCell = row.CreateCell(j);

                switch (dt.Columns[j].DataType.ToString())
                {
                    case "System.String"://字符串类型    
                        newCell.SetCellValue(cellText);
                        break;
                    case "System.DateTime"://日期类型    
                    case "MySql.Data.Types.MySqlDateTime": //MySql类型  
                        if (cellText == "0000/0/0 0:00:00" || String.IsNullOrEmpty(cellText))
                        {
                            //当时间为空，防止生成的execl 中是一串“#######”号，所有赋值为空字符串  
                            newCell.SetCellValue("");
                        }
                        else
                        {
                            DateTime.TryParse(cellText, out DateTime dateV);
                            newCell.SetCellValue(dateV);

                            newCell.CellStyle = dateStyle;//格式化显示    
                        }
                        break;
                    case "System.Boolean"://布尔型    
                        bool boolV;
                        bool.TryParse(cellText, out boolV);
                        newCell.SetCellValue(boolV);
                        break;
                    case "System.Int16"://整型    
                    case "System.Int32":
                    case "System.Int64":
                    case "System.Byte":
                        int intV;
                        int.TryParse(cellText, out intV);
                        newCell.SetCellValue(intV);
                        break;
                    case "System.Decimal"://浮点型    
                    case "System.Double":
                        double doubV;
                        double.TryParse(cellText, out doubV);
                        newCell.SetCellValue(doubV);
                        break;
                    case "System.DBNull"://空值处理    
                        newCell.SetCellValue("");
                        break;
                    default:
                        newCell.SetCellValue("");
                        break;
                }
            }
            //记录主合并的行号
            int jlrow = 0;
            //从第二行开始循环，和上一行进行判断，如果相同，则合并
            for (int i = 1; i < dt.Rows.Count; i++)
            {
                row = sheet.CreateRow(i + 1);
                for (int j = 0; j < dt.Columns.Count; j++)
                {
                    string cellText = dt.Rows[i][j].ToString();

                    var newCell = row.CreateCell(j);

                    switch (dt.Columns[j].DataType.ToString())
                    {
                        case "System.String"://字符串类型    
                            newCell.SetCellValue(cellText);
                            break;
                        case "System.DateTime"://日期类型    
                        case "MySql.Data.Types.MySqlDateTime": //MySql类型  
                            if (cellText == "0000/0/0 0:00:00" || String.IsNullOrEmpty(cellText))
                            {
                                //当时间为空，防止生成的execl 中是一串“#######”号，所有赋值为空字符串  
                                newCell.SetCellValue("");
                            }
                            else
                            {
                                DateTime.TryParse(cellText, out DateTime dateV);
                                newCell.SetCellValue(dateV);

                                newCell.CellStyle = dateStyle;//格式化显示    
                            }
                            break;
                        case "System.Boolean"://布尔型    
                            bool boolV;
                            bool.TryParse(cellText, out boolV);
                            newCell.SetCellValue(boolV);
                            break;
                        case "System.Int16"://整型    
                        case "System.Int32":
                        case "System.Int64":
                        case "System.Byte":
                            int intV;
                            int.TryParse(cellText, out intV);
                            newCell.SetCellValue(intV);
                            break;
                        case "System.Decimal"://浮点型    
                        case "System.Double":
                            double doubV;
                            double.TryParse(cellText, out doubV);
                            newCell.SetCellValue(doubV);
                            break;
                        case "System.DBNull"://空值处理    
                            newCell.SetCellValue("");
                            break;
                        default:
                            newCell.SetCellValue("");
                            break;
                    }
                    //获取上一行数据
                    string temp = dt.Rows[i - 1][j].ToString();
                    //如果是列是1，则不判断合并列的行数
                    if (j == 0)
                    {
                        //temp上一行数据，一定要判断是否为空！！！j< dt.Columns.Count-7，不需要合并的列，也可以改成 && (j!=5 || j!=7)
                        if (!string.IsNullOrEmpty(temp) && cellText == temp && j < dt.Columns.Count - noColumns)
                        {
                            if (j == 0)
                            {
                                //记录主合并的行号
                                jlrow = i + 1;
                            }
                            //本行和上一行合并,为什么是 i和i+1，这里是从第几行开始合并，到第几行结束，i是在dt里的行数，而在表里，因为有表头，所以必须要加1
                            CellRangeAddress region = new CellRangeAddress(i, i + 1, j, j);
                            sheet.AddMergedRegion(region);
                        }
                    }
                    else
                    {
                        //temp上一行数据，一定要判断是否为空！！！j< dt.Columns.Count-7，不需要合并的列，也可以改成 && (j!=5 || j!=7)
                        if (!string.IsNullOrEmpty(temp) && cellText == temp && j < dt.Columns.Count - noColumns && jlrow == i + 1)
                        {
                            //本行和上一行合并,为什么是 i和i+1，这里是从第几行开始合并，到第几行结束，i是在dt里的行数，而在表里，因为有表头，所以必须要加1
                            CellRangeAddress region = new CellRangeAddress(i, i + 1, j, j);
                            sheet.AddMergedRegion(region);
                        }
                    }

                }
            }
            style.Alignment = HorizontalAlignment.Center;
            style.VerticalAlignment = VerticalAlignment.Center;
            NpoiMemoryStream ms = new NpoiMemoryStream
            {
                //System.Web.HttpContext.Current.Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}.xls", HttpUtility.UrlEncode(title + "_" + DateTime.Now.ToString("yyyy-MM-dd_HHmmss"), System.Text.Encoding.UTF8)));
                //System.Web.HttpContext.Current.Response.BinaryWrite(ms.ToArray());
                //System.Web.HttpContext.Current.Response.End();
                AllowClose = false
            };
            book.Write(ms);
            ms.Flush();
            ms.Seek(0, SeekOrigin.Begin);
            ms.AllowClose = true;
            return ms;
        }
        /// <summary>
        /// Excel导入成Datable
        /// </summary>
        /// <param name="file">导入路径(包含文件名与扩展名)</param>
        /// <returns></returns>
        public static DataTable ExcelToTable(string file)
        {
            DataTable dt = new DataTable();
            IWorkbook workbook;
            string fileExt = Path.GetExtension(file).ToLower();
            using (FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read))
            {
                //XSSFWorkbook 适用XLSX格式，HSSFWorkbook 适用XLS格式
                if (fileExt == ".xlsx") { workbook = new XSSFWorkbook(fs); } else if (fileExt == ".xls") { workbook = new HSSFWorkbook(fs); } else { workbook = null; }
                if (workbook == null) { return null; }
                ISheet sheet = workbook.GetSheetAt(0);

                //表头  
                IRow header = sheet.GetRow(sheet.FirstRowNum);
                List<int> columns = new List<int>();
                for (int i = 0; i < header.LastCellNum; i++)
                {
                    object obj = GetValueType(header.GetCell(i));
                    if (obj == null || obj.ToString() == string.Empty)
                    {
                        dt.Columns.Add(new DataColumn("Columns" + i.ToString()));
                    }
                    else
                        dt.Columns.Add(new DataColumn(obj.ToString()));
                    columns.Add(i);
                }
                //数据  
                for (int i = sheet.FirstRowNum + 1; i <= sheet.LastRowNum; i++)
                {
                    DataRow dr = dt.NewRow();
                    bool hasValue = false;
                    foreach (int j in columns)
                    {
                        dr[j] = GetValueType(sheet.GetRow(i).GetCell(j));
                        if (dr[j] != null && dr[j].ToString() != string.Empty)
                        {
                            hasValue = true;
                        }
                    }
                    if (hasValue)
                    {
                        dt.Rows.Add(dr);
                    }
                }
            }
            return dt;
        }

        /// <summary>
        /// Datable导出成Excel
        /// </summary>
        /// <param name="dt"></param>
        /// <param name="file">包括文件名与扩展名</param>
        public static MemoryStream TableToExcel(DataTable dt, string file)
        {
            IWorkbook workbook;

            string fileExt = Path.GetExtension(file).ToLower();
            if (fileExt == ".xlsx") { workbook = new XSSFWorkbook(); } else if (fileExt == ".xls") { workbook = new HSSFWorkbook(); } else { workbook = null; }
            if (workbook == null) { return null; }

            var dateStyle = workbook.CreateCellStyle();
            var format = workbook.CreateDataFormat();
            dateStyle.DataFormat = format.GetFormat("yyyy-mm-dd");

            ISheet sheet = string.IsNullOrEmpty(dt.TableName) ? workbook.CreateSheet("Sheet1") : workbook.CreateSheet(dt.TableName);

            //表头  
            IRow row = sheet.CreateRow(0);
            for (int i = 0; i < dt.Columns.Count; i++)
            {
                ICell cell = row.CreateCell(i);
                cell.SetCellValue(dt.Columns[i].ColumnName);
            }

            //数据  
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                IRow row1 = sheet.CreateRow(i + 1);
                for (int j = 0; j < dt.Columns.Count; j++)
                {

                    string cellText = dt.Rows[i][j].ToString();

                    ICell newCell = row1.CreateCell(j);

                    switch (dt.Columns[j].DataType.ToString())
                    {
                        case "System.String"://字符串类型    
                            newCell.SetCellValue(cellText);
                            break;
                        case "System.DateTime"://日期类型    
                        case "MySql.Data.Types.MySqlDateTime": //MySql类型  
                            if (cellText == "0000/0/0 0:00:00" || String.IsNullOrEmpty(cellText))
                            {
                                //当时间为空，防止生成的execl 中是一串“#######”号，所有赋值为空字符串  
                                newCell.SetCellValue("");
                            }
                            else
                            {
                                DateTime.TryParse(cellText, out DateTime dateV);
                                newCell.SetCellValue(dateV);

                                newCell.CellStyle = dateStyle;//格式化显示    
                            }
                            break;
                        case "System.Boolean"://布尔型    
                            bool boolV;
                            bool.TryParse(cellText, out boolV);
                            newCell.SetCellValue(boolV);
                            break;
                        case "System.Int16"://整型    
                        case "System.Int32":
                        case "System.Int64":
                        case "System.Byte":
                            int intV;
                            int.TryParse(cellText, out intV);
                            newCell.SetCellValue(intV);
                            break;
                        case "System.Decimal"://浮点型    
                        case "System.Double":
                            double doubV;
                            double.TryParse(cellText, out doubV);
                            newCell.SetCellValue(doubV);
                            break;
                        case "System.DBNull"://空值处理    
                            newCell.SetCellValue("");
                            break;
                        default:
                            newCell.SetCellValue("");
                            break;
                    }
                }
            }

            NpoiMemoryStream ms = new NpoiMemoryStream
            {
                AllowClose = false
            };
            workbook.Write(ms);
            ms.Flush();
            ms.Seek(0, SeekOrigin.Begin);
            ms.AllowClose = true;
            return ms;

            ////转为字节数组  
            //MemoryStream stream = new MemoryStream();
            //workbook.Write(stream);
            //var buf = stream.ToArray();

            ////保存为Excel文件  
            //using (FileStream fs = new FileStream(file, FileMode.Create, FileAccess.Write))
            //{
            //    fs.Write(buf, 0, buf.Length);
            //    fs.Flush();
            //}
        }

        /// <summary>
        /// 获取单元格类型
        /// </summary>
        /// <param name="cell"></param>
        /// <returns></returns>
        private static object GetValueType(ICell cell)
        {
            if (cell == null)
                return null;
            switch (cell.CellType)
            {
                case CellType.Blank: //BLANK:  
                    return null;
                case CellType.Boolean: //BOOLEAN:  
                    return cell.BooleanCellValue;
                case CellType.Numeric: //NUMERIC:  
                    return cell.NumericCellValue;
                case CellType.String: //STRING:  
                    return cell.StringCellValue;
                case CellType.Error: //ERROR:  
                    return cell.ErrorCellValue;
                default:
                    return "=" + cell.CellFormula;
            }
        }
        #endregion
    }
}